package com.ezops.poc.parser;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import org.apache.camel.dataformat.bindy.BindyAbstractFactory;
import org.apache.camel.dataformat.bindy.BindyCsvFactory;
import org.apache.camel.dataformat.bindy.csv.BindyCsvDataFormat;
import org.apache.camel.spi.PackageScanClassResolver;

/**
 * This class changes the behavior of BindyCsvDataFormat. Instead of detecting
 * classes in package(s) which are annotated with bindy annotations, this class,
 * specifically defines the class that will be unmarshalled into.
 */
public class SingleClassBindyCsvDataFormat extends BindyCsvDataFormat {

	private Class<?> modelClass;

	@Override
	protected BindyAbstractFactory createModelFactory(
			PackageScanClassResolver resolver) throws Exception {
		return new OneClassBindyCsvFactory(resolver, getModelClass());
	}

	@Override
	public void setPackages(String... packages) {
		throw new UnsupportedOperationException(
				"This dataformat does not support package based model searches.");
	}

	public Class<?> getModelClass() {
		return modelClass;
	}

	public void setModelClass(Class<?> modelClass) {
		this.modelClass = modelClass;
	}

	private static class OneClassBindyCsvFactory extends BindyCsvFactory {

		public OneClassBindyCsvFactory(PackageScanClassResolver resolver,
				Class<?> modelClass) throws Exception {
			super(resolver, new String[] {});
			models = this.<Class<?>> of(modelClass);

			initCsvModel();
		}

		public static <E> Set<E> of(final E e1) {
			Set<E> set = new HashSet<E>(1, 1);
			set.add(e1);

			return Collections.unmodifiableSet(set);
		}

	}

}
